<template>
  <div class="add-wrap">
    <div class="add-wrap__haschose" v-if="choseType">
      <div class="folder-tree">
        <a-menu
          mode="inline"
          :default-selected-keys="[0]"
          :open-keys="openKeys"
          style="width: 256px"
          @openChange="onOpenChange"
        >
          <a-sub-menu key="sub1">
            <span slot="title">
              <a-icon type="folder" />
              <span>函数一</span>
              <div class="actions">
                <a-button type="link" class="addfile" @click.stop="addFile">
                  <a-icon type="file-add" />
                </a-button>
                <a-button type="link" class="editfnname" @click.stop="addFile">
                  <a-icon type="edit" />
                </a-button>
              </div>
            </span>
            <a-menu-item :key="i" v-for="(file, i) in files">
              <a-icon type="file" /><span>{{ file.name }}</span>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </div>
      <div class="add-wrap__edit">
        <a-input
          placeholder="请输入函数名"
          v-model="modulename"
          :readonly="idEdit"
        />
        <div class="editor-wrap">
          <Editor :code="code" @editorDidMount="didMount"></Editor>
        </div>
        <div class="actions">
          <a-button @click="doconfirm">{{ idEdit ? "更新" : "添加" }}</a-button>
        </div>
      </div>
    </div>
    <div class="add-wrap__dochose" v-if="!choseType">
      <p class="title">请选择添加类型</p>
      <div class="modes">
        <div class="mode-item onlineedit" @click="doEdit">在线编辑</div>
        <a-upload name="file" :before-upload="doUpload" :showUploadList="false">
          <div class="mode-item uploadfile">从文件编辑</div>
        </a-upload>
      </div>
    </div>
  </div>
</template>

<script>
import Editor from "@/components/editor.vue";
import { parseCode } from "@/utils/codehelper.js";
import { mapState, mapMutations } from "vuex";
export default {
  components: {
    Editor
  },
  data() {
    return {
      choseType: null,
      code: "",
      idEdit: false,
      editor: null,
      openKeys: ["sub1"],
      files: [],
      modulename: "",
      rootSubmenuKeys: ["sub1"]
    };
  },
  computed: {
    ...mapState("function", ["name"])
  },
  created() {
    const query = this.$route.query;
    if (query && query.id) {
      // 修改
      this.idEdit = true;
      this.choseType = 1;
      this.getSourceCode({
        id: +query.id,
        cb: data => {
          if (!data) {
            this.idEdit = false;
            this.files = [
              {
                key: 1,
                name: "index.js"
              }
            ];
            return;
          }
          this.code = data.scriptContent;
          this.modulename = data.moduleName;
          this.files = [
            {
              key: 1,
              name: data.moduleName + ".js"
            }
          ];
        }
      });
    } else {
      this.idEdit = false;
      this.files = [
        {
          key: 1,
          name: "index.js"
        }
      ];
    }
  },
  methods: {
    ...mapMutations("function", ["getFunc"]),
    didMount(editor) {
      this.editor = editor;
      editor.setValue(this.code);
    },
    getSourceCode(data) {
      return this.getFunc(data);
    },
    addFile() {
      this.files.push({
        key: this.files.length + 1,
        name: "name" + (this.files.length + 1) + ".js"
      });
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(
        key => this.openKeys.indexOf(key) === -1
      );
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys;
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },
    addfunc() {
      const code = this.editor.getValue();
      const packages = parseCode(code);
      return this.$cloud.addCloud(this.modulename, {
        Packages: packages,
        ScriptContext: code
      });
    },
    updatefunc() {
      const code = this.editor.getValue();
      const packages = parseCode(code);
      return this.$cloud.updateCloud(this.modulename, {
        Packages: packages,
        ScriptContext: code
      });
    },
    doconfirm() {
      if (!this.modulename) {
        this.$$message.error("请输入函数名");
        return;
      }
      if (!this.idEdit) {
        this.addfunc().then(res => {
          if (res) {
            this.$message.success("提交成功");
          }
        });
      } else {
        this.updatefunc().then(res => {
          if (res) {
            this.$message.success("更新成功");
          }
        });
      }
    },
    doEdit() {
      this.code = `/***
 * iTool Code template (Title)
 * Author：Jian
 * Date：2020/08/30
 * Description： iTool This is cloud function.
 */

/***
 * const packgName = require('sha1');  导入 npm 包
 * const module = require('./moduleName');  导入其它业务模块，支持相对路径
 */

module.exports = function(callback, arg1, arg2) {

  var result = {};

  /***
   * 处理你的业务逻辑
   * result = module(callback,arg1);
   */
  
  // ... 

  // callback(Error,OkResult type must is [Json/Array])
  callback(null, result);

}`;
      this.choseType = 1;
    },
    doUpload(file) {
      if (file.type === "text/javascript") {
        const reader = new FileReader();
        reader.onload = () => {
          if (reader.result) {
            this.code = reader.result;
            this.choseType = 2;
          }
        };
        reader.readAsText(file);
      } else {
        this.$message.info("请上传js类型的文件");
      }
      return false;
    }
  }
};
</script>

<style lang="less">
.add-wrap {
  height: 100%;
  .add-wrap__haschose {
    display: flex;
    height: 100%;
    .folder-tree {
      .ant-menu-submenu-title {
        // background: #eee;
        margin: 0;
        .actions {
          display: none;
          float: right;
          .ant-btn {
            padding: 0;
            border: none;
          }
        }
        &:hover {
          .actions {
            display: block;
          }
        }
      }
      .ant-menu-item {
        margin: 0;
      }
    }
    .add-wrap__edit {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      margin-left: 10px;
      .editor-wrap {
        margin-top: 10px;
        flex: 1;
        overflow: hidden;
      }
      .actions {
        margin-top: 10px;
        .ant-btn {
          margin-right: 10px;
        }
      }
    }
  }
  .add-wrap__dochose {
    display: flex;
    flex-direction: column;
    .title {
      font-size: 18px;
      text-align: center;
      line-height: 50px;
    }
    .modes {
      flex: 1;
      display: flex;
      padding-top: 100px;
      flex-direction: row;
      justify-content: center;
      .mode-item {
        border: 1px solid #eee;
        border-radius: 4px;
        width: 240px;
        height: 320px;
        text-align: center;
        cursor: pointer;
        line-height: 320px;
        &.onlineedit {
          margin-right: 100px;
        }
      }
    }
  }
}
</style>
